package com.blockchain.console.service.financial.achieve;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import com.blockchain.common.enums.GdState;
import com.blockchain.common.enums.ZfType;
import com.blockchain.console.config.ConsoleConst;
import com.blockchain.console.service.financial.GdglManage;
import com.blockchain.console.service.financial.entity.GdglRecord;
import com.blockchain.console.service.financial.query.GdglRecordQuery;
import com.blockchain.framework.data.sql.SQLConnectionProvider;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.exception.ParameterException;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.framework.service.query.ItemParser;
import com.blockchain.framework.service.query.Paging;
import com.blockchain.framework.service.query.PagingResult;
import com.blockchain.util.StringHelper;
import com.blockchain.util.parser.EnumParser;
import com.blockchain.variables.P2PConst;

public class GdglManageImpl extends AbstractFinancialService implements
		GdglManage {

	public static class ExtractionManageFactory implements
			ServiceFactory<GdglManage> {

		@Override
		public GdglManage newInstance(ServiceResource serviceResource) {
			return new GdglManageImpl(serviceResource);
		}
	}

	public GdglManageImpl(ServiceResource serviceResource) {
		super(serviceResource);

	}

	@Override
	public PagingResult<GdglRecord> search(GdglRecordQuery query, Paging paging) throws Throwable {
		StringBuilder sql = new StringBuilder(
				"SELECT T1.F01 AS F01, T2.F02 AS F02, T3.F02 name,")
				.append("T1.F02 AS F04, T1.F03 AS F05,")
				.append("T1.F04 AS F06, T1.F05 AS F07, T1.F06 AS F08, T1.F07 AS F09,")
				.append("T1.F08 AS F10,T1.F09 AS F11,T1.F10 AS F12,T1.F11 AS F13,T1.F12 as F14,T1.F13 as F15")
				.append(" FROM T6040 T1");
				sql.append(" LEFT JOIN T6010 T2 ON T1.F02 = T2.F01");
				sql.append(" LEFT JOIN T6011 T3 ON T1.F02 = T3.F01  WHERE 1=1");
				ArrayList<Object> parameters = new ArrayList<>();
				if (query != null) {
					SQLConnectionProvider sqlConnectionProvider = getSQLConnectionProvider();
					
					int lsj = query.getLsh();
					String yhm = query.getYhm();
					String xm = query.getXm();
					GdState status = query.getStatus();
					if (lsj > 0) {
						sql.append(" AND T1.F01 = ?");
						parameters.add(lsj);
					}
					if (!StringHelper.isEmpty(yhm)) {
						sql.append(" AND  T2.F02 LIKE ?");
						parameters.add(sqlConnectionProvider.allMatch(yhm));
					}
					if (!StringHelper.isEmpty(xm)) {
						sql.append(" AND  T3.F02 LIKE ?");
						parameters.add(sqlConnectionProvider.allMatch(xm));
					}
					Timestamp datetime = query.getStartExtractionTime();
					if (datetime != null) {
						if (status == GdState.DSH || status == GdState.SHSB || status == GdState.GDZ) {
							sql.append(" AND DATE(T1.F08)>=?");
						} else if (status == GdState.YPX) {
							sql.append(" AND DATE(T1.F11)>=?");
						} else if (status == GdState.JYCG) {
							sql.append(" AND DATE(T1.F12)>=?");
						}
						parameters.add(datetime);
					}
					datetime = query.getEndExtractionTime();
					if (datetime != null) {
						if (status == GdState.DSH || status == GdState.SHSB || status == GdState.GDZ) {
							sql.append(" AND DATE(T1.F08)<=?");
						} else if (status == GdState.YPX) {
							sql.append(" AND DATE(T1.F11)<=?");
						} else if (status == GdState.JYCG) {
							sql.append(" AND DATE(T1.F12)<=?");
						}
						parameters.add(datetime);
					}
					if (status != null) {
						sql.append(" AND T1.F09=?");
						parameters.add(status);
					}
				}
				return selectPaging(getConnection(ConsoleConst.DB_USER),
						new ArrayParser<GdglRecord>() {
							ArrayList<GdglRecord> list = new ArrayList<GdglRecord>();

							public GdglRecord[] parse(ResultSet rst)
									throws SQLException {
								while (rst.next()) {
									GdglRecord user = new GdglRecord();
									user.id = rst.getInt(1);
									user.loginName = rst.getString(2);
									user.userName = rst.getString(3);
									user.sellId = rst.getInt(4);
									user.gdsl = rst.getBigDecimal(5);
									user.zfType = EnumParser.parse(ZfType.class, rst.getString(6));
									user.skzh = rst.getString(7);
									user.gddj = rst.getBigDecimal(8);
									user.lxdh = rst.getString(9);
									user.gdsj = rst.getTimestamp(10);
									user.gdState = EnumParser.parse(GdState.class, rst.getString(11));
									user.sysl = rst.getBigDecimal(12);
									user.zxcjsl = rst.getBigDecimal(13);
									user.cjsj = rst.getTimestamp(14);
									user.bz = rst.getString(15);
									list.add(user);
								}
								return list.toArray(new GdglRecord[list.size()]);
							}
						}, paging, sql.toString(), parameters);
	}

	@Override
	public GdglRecord get(int id) throws Throwable {
		if (id <= 0) {
			throw new ParameterException("指定的记录不存在.");
		}
		StringBuilder sql = new StringBuilder(
				"SELECT T1.F01 AS F01, T2.F02 AS F02, T3.F02 name,")
		.append("T1.F02 AS F04, T1.F03 AS F05,")
		.append("T1.F04 AS F06, T1.F05 AS F07, T1.F06 AS F08, T1.F07 AS F09,")
		.append("T1.F08 AS F10,T1.F09 AS F11,T1.F10 AS F12,T1.F11 AS F13,T1.F12 as F14,T1.F14 as F15")
		.append(" FROM T6040 T1");
		sql.append(" LEFT JOIN T6010 T2 ON T1.F02 = T2.F01");
		sql.append(" LEFT JOIN T6011 T3 ON T1.F02 = T3.F01");
		sql.append(" WHERE T1.F01=?");
		return select(getConnection(ConsoleConst.DB_USER),
				new ItemParser<GdglRecord>() {
					public GdglRecord parse(ResultSet rst) throws SQLException {
						GdglRecord user = new GdglRecord();
						if (rst.next()) {
							user.id = rst.getInt(1);
							user.loginName = rst.getString(2);
							user.userName = rst.getString(3);
							user.sellId = rst.getInt(4);
							user.gdsl = rst.getBigDecimal(5);
							user.zfType = EnumParser.parse(ZfType.class, rst.getString(6));
							user.skzh = rst.getString(7);
							user.gddj = rst.getBigDecimal(8);
							user.lxdh = rst.getString(9);
							user.gdsj = rst.getTimestamp(10);
							user.gdState = EnumParser.parse(GdState.class, rst.getString(11));
							user.sysl = rst.getBigDecimal(12);
							user.zxcjsl = rst.getBigDecimal(13);
							user.cjsj = rst.getTimestamp(14);
							user.gdsxf = rst.getBigDecimal(15);
						}
						return user;
					}
				}, sql.toString(), id);
	}

	@Override
	public void check(GdState status, String check_reason, int id,GdglRecord gdglRecord) throws Throwable {
		if (id <= 0) {
			throw new ParameterException("指定的记录不存在.");
		}
		String update = "UPDATE T6040 SET F09=?,F13=? WHERE F01=?";
		if (status == GdState.GDZ) {
			execute(getConnection(ConsoleConst.DB_USER), update, status,
					check_reason, id);
		}else if (status == GdState.SHSB) {
			BigDecimal sjje = gdglRecord.gdsl.add(gdglRecord.gdsxf);
			execute(getConnection(ConsoleConst.DB_USER), update, status,
					check_reason, id);
			selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6023 WHERE F01=? FOR UPDATE", gdglRecord.sellId);
			execute(getConnection(P2PConst.DB_USER), "UPDATE T6023 SET F03=F03-?,F04=F04+? WHERE F01=?", sjje,sjje, gdglRecord.sellId);
		}else if(status == GdState.JYCG) {
			BigDecimal sjje = gdglRecord.gdsl.add(gdglRecord.gdsxf);
			update = "UPDATE T6040 SET F09=?,F12=CURRENT_TIMESTAMP() WHERE F01=?";
			execute(getConnection(ConsoleConst.DB_USER), update, status,id);
			selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6023 WHERE F01=? FOR UPDATE", gdglRecord.sellId);
			execute(getConnection(P2PConst.DB_USER), "UPDATE T6023 SET F02=F02-?,F03=F03-? WHERE F01=?", sjje, sjje, gdglRecord.sellId);
			selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6023 WHERE F01=? FOR UPDATE", gdglRecord.buyId);
			execute(getConnection(P2PConst.DB_USER), "UPDATE T6023 SET F02=F02+?,F04=F04+? WHERE F01=?", gdglRecord.gdsl,gdglRecord.gdsl, gdglRecord.buyId);
		}else if (status == GdState.QZQX) {
			execute(getConnection(ConsoleConst.DB_USER), update, GdState.GDZ,
					check_reason, id);
		}
	}

	@Override
	public PagingResult<GdglRecord> searchYpx(GdglRecordQuery query, Paging paging) throws Throwable {
		StringBuilder sql = new StringBuilder(
				"SELECT T1.F01 AS F01, T1.F02 AS F02, T1.F03 AS F03,")
		.append("T1.F04 AS F04, T1.F05 AS F05,T1.F06 AS F06,")
		.append("T2.F02 AS F07, T2.F03 AS F08,T2.F04 AS F09,T2.F05 AS F10,T2.F06 AS F11,T2.F07 AS F12,T2.F08 AS F13,")
		.append("T2.F10 AS F14,T2.F11 AS F15,T2.F14 AS F16,T2.F15 AS F17,T2.F16 AS F18,T2.F17 AS F19,T2.F18 AS F20,T2.F19 AS F21,")
		.append(" T3.F02 AS F22,T4.F02 AS F23,T5.F02 AS F24,T6.F02 AS F25")
		.append(" FROM T6041 T1");
		sql.append(" LEFT JOIN T6040 T2 ON T1.F02 = T2.F01");
		sql.append(" LEFT JOIN T6010 T3 ON T2.F02 = T3.F01");
		sql.append(" LEFT JOIN T6011 T4 ON T2.F02 = T4.F01");
		sql.append(" LEFT JOIN T6010 T5 ON T1.F04 = T5.F01");
		sql.append(" LEFT JOIN T6011 T6 ON T1.F04 = T6.F01  WHERE 1=1");
				ArrayList<Object> parameters = new ArrayList<>();
				if (query != null) {
					SQLConnectionProvider sqlConnectionProvider = getSQLConnectionProvider();
					
					int lsj = query.getLsh();
					String yhm = query.getYhm();
					String xm = query.getXm();
					GdState status = query.getStatus();
					if (lsj > 0) {
						sql.append(" AND T1.F01 = ?");
						parameters.add(lsj);
					}
					if (!StringHelper.isEmpty(yhm)) {
						sql.append(" AND  T3.F02 LIKE ?");
						parameters.add(sqlConnectionProvider.allMatch(yhm));
					}
					if (!StringHelper.isEmpty(xm)) {
						sql.append(" AND  T4.F02 LIKE ?");
						parameters.add(sqlConnectionProvider.allMatch(xm));
					}
					Timestamp datetime = query.getStartExtractionTime();
					if (datetime != null) {
						if (status == GdState.JYCG) {
							sql.append(" AND DATE(T1.F12)>=?");
						} else {
							sql.append(" AND DATE(T1.F08)>=?");
						}
						parameters.add(datetime);
					}
					datetime = query.getEndExtractionTime();
					if (datetime != null) {
						if (status == GdState.JYCG) {
							sql.append(" AND DATE(T1.F12)<=?");
						} else {
							sql.append(" AND DATE(T1.F08)<=?");
						}
						parameters.add(datetime);
					}
					if (status != null) {
						sql.append(" AND T1.F06=?");
						parameters.add(status);
					}
				}
				return selectPaging(getConnection(ConsoleConst.DB_USER),
						new ArrayParser<GdglRecord>() {
							ArrayList<GdglRecord> list = new ArrayList<GdglRecord>();

							public GdglRecord[] parse(ResultSet rst)
									throws SQLException {
								while (rst.next()) {
									GdglRecord user = new GdglRecord();
									user.pdid = rst.getInt(1);
									user.id = rst.getInt(2);
									user.pdsl = rst.getBigDecimal(3);
									user.buyId = rst.getInt(4);
									user.pdsj = rst.getTimestamp(5);
									user.pdState = EnumParser.parse(GdState.class, rst.getString(6));
									user.sellId = rst.getInt(7);
									user.gdsl = rst.getBigDecimal(8);
									user.zfType = EnumParser.parse(ZfType.class, rst.getString(9));
									user.skzh = rst.getString(10);
									user.gddj = rst.getBigDecimal(11);
									user.lxdh = rst.getString(12);
									user.gdsj = rst.getTimestamp(13);
									user.sysl = rst.getBigDecimal(14);
									user.zxcjsl = rst.getBigDecimal(15);
									user.gdsxf = rst.getBigDecimal(16);
									if (user.zfType == ZfType.YHK) {
										user.yhmc = rst.getString(17);
										user.sheng = rst.getString(18);
										user.shi = rst.getString(19);
										user.zhmc = rst.getString(20);
										user.khxm = rst.getString(21);
									}
									user.bloginName = rst.getString(22);
									user.buserName = rst.getString(23);
									user.loginName = rst.getString(24);
									user.userName = rst.getString(25);
									list.add(user);
								}
								return list.toArray(new GdglRecord[list.size()]);
							}
						}, paging, sql.toString(), parameters);
	}

	@Override
	public GdglRecord getPd(int id) throws Throwable {
		if (id <= 0) {
			throw new ParameterException("指定的记录不存在.");
		}
		StringBuilder sql = new StringBuilder(
				"SELECT T1.F01 AS F01, T1.F02 AS F02, T1.F03 AS F03,")
		.append("T1.F04 AS F04, T1.F05 AS F05,T1.F06 AS F06,")
		.append("T2.F02 AS F07, T2.F03 AS F08,T2.F04 AS F09,T2.F05 AS F10,T2.F06 AS F11,T2.F07 AS F12,T2.F08 AS F13,")
		.append("T2.F10 AS F14,T2.F11 AS F15,T2.F14 AS F16,T2.F15 AS F17,T2.F16 AS F18,T2.F17 AS F19,T2.F18 AS F20,T2.F19 AS F21,")
		.append(" T3.F02 AS F22,T4.F02 AS F23,T5.F02 AS F24,T6.F02 AS F25")
		.append(" FROM T6041 T1");
		sql.append(" LEFT JOIN T6040 T2 ON T1.F02 = T2.F01");
		sql.append(" LEFT JOIN T6010 T3 ON T2.F02 = T3.F01");
		sql.append(" LEFT JOIN T6011 T4 ON T2.F02 = T4.F01");
		sql.append(" LEFT JOIN T6010 T5 ON T1.F04 = T5.F01");
		sql.append(" LEFT JOIN T6011 T6 ON T1.F04 = T6.F01  WHERE T1.F01=?");
		return select(getConnection(ConsoleConst.DB_USER),
				new ItemParser<GdglRecord>() {
					public GdglRecord parse(ResultSet rst) throws SQLException {
						GdglRecord user = new GdglRecord();
						if (rst.next()) {
							user.pdid = rst.getInt(1);
							user.id = rst.getInt(2);
							user.pdsl = rst.getBigDecimal(3);
							user.buyId = rst.getInt(4);
							user.pdsj = rst.getTimestamp(5);
							user.pdState = EnumParser.parse(GdState.class, rst.getString(6));
							user.sellId = rst.getInt(7);
							user.gdsl = rst.getBigDecimal(8);
							user.zfType = EnumParser.parse(ZfType.class, rst.getString(9));
							user.skzh = rst.getString(10);
							user.gddj = rst.getBigDecimal(11);
							user.lxdh = rst.getString(12);
							user.gdsj = rst.getTimestamp(13);
							user.sysl = rst.getBigDecimal(14);
							user.zxcjsl = rst.getBigDecimal(15);
							user.gdsxf = rst.getBigDecimal(16);
							if (user.zfType == ZfType.YHK) {
								user.yhmc = rst.getString(17);
								user.sheng = rst.getString(18);
								user.shi = rst.getString(19);
								user.zhmc = rst.getString(20);
								user.khxm = rst.getString(21);
							}
							user.bloginName = rst.getString(22);
							user.buserName = rst.getString(23);
							user.loginName = rst.getString(24);
							user.userName = rst.getString(25);
						}
						return user;
					}
				}, sql.toString(), id);
	}

	@Override
	public void checkSu(GdState status, int id, GdglRecord gdglRecord) throws Throwable {
		serviceResource.openTransactions();
		try {
		if (id <= 0) {
			throw new ParameterException("指定的记录不存在.");
		}
		String update = "UPDATE T6040 SET F09=?,F13=? WHERE F01=?";
		if(status == GdState.JYCG) {
			BigDecimal sxfl = gdglRecord.gdsxf.divide(gdglRecord.gdsl);
			update = "UPDATE T6041 SET F06=? WHERE F01=?";
			execute(getConnection(ConsoleConst.DB_USER), update, status,id);
			selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6023 WHERE F01=? FOR UPDATE", gdglRecord.sellId);
			execute(getConnection(P2PConst.DB_USER), "UPDATE T6023 SET F02=F02-?,F03=F03-? WHERE F01=?", gdglRecord.pdsl, gdglRecord.pdsl.add(gdglRecord.pdsl.multiply(sxfl)), gdglRecord.sellId);
			selectInt(P2PConst.DB_USER, "SELECT F01 FROM T6023 WHERE F01=? FOR UPDATE", gdglRecord.buyId);
			execute(getConnection(P2PConst.DB_USER), "UPDATE T6023 SET F02=F02+?,F04=F04+? WHERE F01=?", gdglRecord.pdsl, gdglRecord.pdsl, gdglRecord.buyId);
		}else if (status == GdState.QZQX) {
			execute(getConnection(P2PConst.DB_USER), "UPDATE T6041 SET F06=? WHERE F01=?",GdState.YQX, id);
			execute(getConnection(P2PConst.DB_USER), "UPDATE T6040 SET F10=F10+? WHERE F01=?",gdglRecord.pdsl, gdglRecord.id);
		}
		} catch (Exception e) {
			serviceResource.rollback();
			e.printStackTrace();
			throw new ParameterException(e.getMessage());
		}
	}
	
}
